package idao.engine;

import idao.engine.executor.SqlExecutor;

import java.lang.reflect.Method;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;

/**
 * Stores method metadata of a dao method.
 * 
 * @author huhao
 */
public final class DaoMethod
{

    private static Map<Method, DaoMethod> DAO_METHODS = new HashMap<Method, DaoMethod>();

    public static DaoMethod getDaoMethod(Method m)
    {
        DaoMethod daoMethod = DAO_METHODS.get(m);
        if (daoMethod == null) {
            synchronized (DAO_METHODS) {
                // at this time, another thread may have already put one
                // into the cache, so do not put unless no one else did it.
                daoMethod = DAO_METHODS.get(m);
                if (daoMethod == null) {
                    daoMethod = new DaoMethod(m);
                    DAO_METHODS.put(m, daoMethod);
                }
            }
        }
        return daoMethod;
    }

    private SqlExecutor executor;

    DaoMethod(Method m)
    {
        executor = SqlExecutor.getExecutor(m);
    }

    public Object invoke(Connection c, Object[] args)
    {
        return executor.execute(c, args);
    }
}
